package com.eden.door.view;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.eden.door.component.CGTextField;
import com.eden.door.component.DoorTableModel;
import com.eden.door.component.ImageRenderer;
import com.eden.door.constant.Constant_Sys;
import com.eden.door.constant.Constant_View;
import com.eden.door.context.AppContext;
import com.eden.door.entity.Door;
import com.eden.door.entity.DoorAttr;
import com.eden.door.entity.Option;
import com.eden.door.exception.CgException;
import com.eden.door.listener.TableMouseListener;

/**
 * 展示门的属性,用于计算页面
 * 
 * @author Eden
 * 
 */
public class DoorView {
	private final Log log = LogFactory.getLog(DoorView.class);

	private Door door;
	private JTable table;
	DoorViewPanel doorViewPanel ;
	// 界面上的组件与code 组成的 map
	private Map<String, JComponent> doorAttrJcompMap = new HashMap<String, JComponent>();

	public DoorView(String doorName){
		this.show(doorName) ;
	}
	/**
	 * 返回已经计算好的门
	 * @return
	 */
	public Door getDoorWithValue() {
		door.setDoorAttrs(getDoorAttrWithValue());
		return door;
	}

	/**
	 * 取出界面上所有组件填写的值
	 * 
	 * @return
	 */
	public Map<String, DoorAttr> getDoorAttrWithValue() {
		Map<String, DoorAttr> doorAttrWithValueMap = new HashMap<String, DoorAttr>();
		if (doorAttrJcompMap.size() <= 0) {
			throw new CgException("there is no data in the door attribute map ");
		}

		String type = "";
		String code = "";
		JComponent jcomp = null;
		Map<String, DoorAttr> doorAttrMap = door.getDoorAttrs();
		DoorAttr doorAttr = null;
		Entry<String, JComponent> entry = null;
		String value = "";
		for (Iterator<Entry<String, JComponent>> i = doorAttrJcompMap
				.entrySet().iterator(); i.hasNext();) {
			entry = i.next();
			code = entry.getKey();
			jcomp = entry.getValue();

			doorAttr = doorAttrMap.get(code);
			type = doorAttr.getType();

			// 如果属性的填写类型为manual时,从输入框取值
			if (StringUtils.equals(Constant_Sys.DOOR_ATTR_FILL_MANUAL,
					doorAttr.getFill())) {
				if (StringUtils.equals(Constant_Sys.DOOR_ATTR_TYPE_TEXT, type)) {
					value = (((JTextField) jcomp).getText());
				} else if (StringUtils.equals(
						Constant_Sys.DOOR_ATTR_TYPE_SELECT, type)) {
					value = ((JComboBox) jcomp).getSelectedItem().toString();
				}
				doorAttr.setValue(value);
			}

			doorAttrWithValueMap.put(code, doorAttr);
		}
		return doorAttrWithValueMap;
	}

	/**
	 * 将所有门的属性画到面板上，供用户输入
	 * 
	 * @param actionEvent
	 *            传入的按钮点击事件
	 * @return
	 */
	
	public JComponent show(String doorName) {
		doorViewPanel = new DoorViewPanel() ;
		AppContext context = AppContext.instance();

		door = context.getDoorByName(doorName);

		// 未计算的所有的门的属
		Map<String, DoorAttr> doorAttrMap = door.getDoorAttrs();

		doorViewPanel.getFieldPanel().setLayout(
				new FlowLayout(FlowLayout.LEFT, 10, 20));

		// 取出门的所有属性写到面板里,主要用于计算时
		JPanel group = null;
		JLabel label; // 标签
		JComponent jcomp; // 属性类型,文本框,或者下拉
		int showOrder = 1; // 计算时的显示顺序
		// for(Iterator<Entry<String, DoorAttr>> i =
		// doorAttrMap.entrySet().iterator() ; i.hasNext() ;){
		for (int index = 0, l = doorAttrMap.size(); index < l; index++) {

			DoorAttr doorAttr = null;
			for (Iterator<Entry<String, DoorAttr>> i = doorAttrMap.entrySet()
					.iterator(); i.hasNext();) {
				DoorAttr tempDoorAttr = i.next().getValue();
				if (tempDoorAttr.getShowOrder() == showOrder) {
					doorAttr = tempDoorAttr;
				}

			}
			showOrder++;

			// 如果没有取到值，重新循环
			if (doorAttr == null) {
				log.warn("没有找到显示顺序为：" + (--showOrder) + "的属性");
				continue;
			}

			group = new JPanel();
			group.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
			label = new JLabel(doorAttr.getName() + ":");
			if (StringUtils.equals(doorAttr.getType(),
					Constant_Sys.DOOR_ATTR_TYPE_TEXT)) {
				jcomp = new CGTextField(doorAttr.getValue());
			} else {
				List<Option> temp = doorAttr.getOptList();
				String[] options = new String[temp.size()];
				for (int i1 = 0, length = temp.size(); i1 < length; i1++) {
					options[i1] = temp.get(i1).getText();
				}

				jcomp = new JComboBox(new DefaultComboBoxModel(options));
				jcomp.setPreferredSize(new Dimension(65, 25));
			}

			// 取到门属性code与页面的组件的关系，用于取出用户输入的值
			doorAttrJcompMap.put(doorAttr.getCode(), jcomp);

			group.add(label);
			group.add(jcomp);

			doorViewPanel.getFieldPanel().add(group);

		}

		this.table = doorViewPanel.getTable(); // 外部使用
		
		this.table.addMouseListener(new TableMouseListener(this.table));
		this.table.addMouseMotionListener(new TableMouseListener(this.table));
		// 按printOrder顺序设置表的标题
		String[] columns = new String[doorAttrMap.size() + 2];
		int columnIndex = 1;
		int printOrder = 1;
		columns[0] = "序号";
		for (int index = 0, l = doorAttrMap.size(); index < l; index++) {
			DoorAttr doorAttr = null;

			for (Iterator<Entry<String, DoorAttr>> i = doorAttrMap.entrySet()
					.iterator(); i.hasNext();) {
				doorAttr = i.next().getValue();
				if (doorAttr.getPrintOrder() == printOrder) {
					// 表头
					columns[columnIndex++] = doorAttr.getName();
				}
			}
			printOrder++;
		}
		columns[columnIndex++] = "操作";
		
		JTable table = doorViewPanel.getTable();
		
		// 为表中加入数据
		table.setModel(new DoorTableModel(columns, 10));

		table.setDefaultRenderer(Object.class,
				new TableCellTextAreaRenderer());
		
		// 调整表默认列宽
		table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		TableColumnModel tcm = table.getTableHeader()
				.getColumnModel();
		for (int i = 0; i < tcm.getColumnCount(); i++) {
			TableColumn tc = tcm.getColumn(i);
			tc.setPreferredWidth(Constant_View.COLUMN_PREFER_WIDTH);
			tc.setMinWidth(Constant_View.COLUMN_MIN_WIDTH);
			tc.setMaxWidth(Constant_View.COLUMN_MAX_WIDTH);
		}

		return doorViewPanel;
	}

	public Map<String, JComponent> getDoorAttrJcompMap() {
		return doorAttrJcompMap;
	}

	public void setDoorAttrJcompMap(Map<String, JComponent> doorAttrJcompMap) {
		this.doorAttrJcompMap = doorAttrJcompMap;
	}

	public JTable getTable() {
		return this.table;
	}
	public DoorViewPanel getDoorViewPanel() {
		return doorViewPanel;
	}
	public void setDoorViewPanel(DoorViewPanel doorViewPanel) {
		this.doorViewPanel = doorViewPanel;
	}
}

/**
 * 计算表格的行高度
 * 
 * @author Eden
 * 
 */
class TableCellTextAreaRenderer extends JTextArea implements TableCellRenderer {
	private static final long serialVersionUID = 1L;

	public TableCellTextAreaRenderer() {
		setLineWrap(true);
		setWrapStyleWord(true);
	}

	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean hasFocus, int row, int column) {
		// 设置字体大小
		setFont(new Font("宋体", Font.PLAIN, 20)) ;
		setPreferredSize(new Dimension(10, 20 )) ;
		// 默认高度
		int maxPreferredHeight = Constant_View.DEFAULT_ROW_HEIGHT;
		for (int i = 0; i < table.getColumnCount(); i++) {
			setText("" + table.getValueAt(row, i));
			setSize(table.getColumnModel().getColumn(column).getWidth(), 0);
			maxPreferredHeight = Math.max(maxPreferredHeight,
					getPreferredSize().height);
		}

		if (table.getRowHeight(row) != maxPreferredHeight) // 少了这行则处理器瞎忙
			table.setRowHeight(row, maxPreferredHeight);

		setText(value == null ? "" : value.toString());
		return this;
	}
}
